package com.kcl.dfss.utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.videolan.libvlc.LibVLC;
import org.videolan.libvlc.LibVlcException;
import org.videolan.libvlc.VlcCrashHandler;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;

public class AppUtils {
	public boolean getAppIsFirstRun() {
		return true;
	}

	public static LibVLC getLibVlcInstance(Context context) throws LibVlcException {
		Log.d("Kyle","getLibVlcInstance");
		LibVLC instance = LibVLC.getExistingInstance();
		if (instance == null) {
			Log.d("Kyle", "vlc instance is null, create a new one");
			Thread.setDefaultUncaughtExceptionHandler(new VlcCrashHandler());

			instance = LibVLC.getInstance();
			
			SharedPreferences pref = PreferenceManager
					.getDefaultSharedPreferences(context);
			updateLibVlcSettings(pref);
			instance.init(context);
		}
		return instance;
	}

	public static void updateLibVlcSettings(SharedPreferences pref) {
		LibVLC instance = LibVLC.getExistingInstance();
		if (instance == null)
			return;

		instance.setIomx(pref.getBoolean("enable_iomx", false));
		instance.setSubtitlesEncoding(pref.getString("subtitles_text_encoding",
				""));
		instance.setTimeStretching(pref.getBoolean(
				"enable_time_stretching_audio", false));
		instance.setFrameSkip(pref.getBoolean("enable_frame_skip", false));
		instance.setChroma(pref.getString("chroma_format", ""));
		instance.setVerboseMode(pref.getBoolean("enable_verbose_mode", true));

		if (pref.getBoolean("equalizer_enabled", false))
			instance.setEqualizer(getFloatArray(pref, "equalizer_values"));

		int aout;
		try {
			aout = Integer.parseInt(pref.getString("aout", "-1"));
		} catch (NumberFormatException nfe) {
			aout = -1;
		}
		int vout;
		try {
			vout = Integer.parseInt(pref.getString("vout", "-1"));
		} catch (NumberFormatException nfe) {
			vout = -1;
		}
		int deblocking;
		try {
			deblocking = Integer.parseInt(pref.getString("deblocking", "-1"));
		} catch (NumberFormatException nfe) {
			deblocking = -1;
		}
		int networkCaching = pref.getInt("network_caching_value", 0);
		if (networkCaching > 60000)
			networkCaching = 60000;
		else if (networkCaching < 0)
			networkCaching = 0;
		instance.setAout(aout);
		instance.setVout(vout);
		instance.setDeblocking(deblocking);
		instance.setNetworkCaching(networkCaching);
	}

	public static float[] getFloatArray(SharedPreferences pref, String key) {
		float[] array = null;
		String s = pref.getString(key, null);
		if (s != null) {
			try {
				JSONArray json = new JSONArray(s);
				array = new float[json.length()];
				for (int i = 0; i < array.length; i++)
					array[i] = (float) json.getDouble(i);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return array;
	}
}
